import { StateType } from "@/store";
import React, { useEffect } from "react";
import { useSelector } from "react-redux";
import { useLocation, useNavigate } from "react-router-dom";

interface AuthRouteProps {
  /** 是否需要登录校验 */
  allowed: boolean;
  /** 权限验证失败时的重定向路径 */
  redirectTo: string;
  /** 实际跳转页面 */
  children: React.ReactNode;
}

/**
 * 封装路由跳转权限：
 * 1. 未登录时，不允许访问需要登录权限的页面
 * 2. 已登录时，不允许访问登录页面
 */
const AuthRoute: React.FC<AuthRouteProps> = ({
  allowed,
  redirectTo,
  children,
}) => {
  const nav = useNavigate();
  const { pathname } = useLocation();

  // 判断用户是否登录
  const token = useSelector((state: StateType) => state.authSlice.token);
  const isLogin = !!token;
  console.log("路由跳转校验：", pathname, token);

  useEffect(() => {
    if (allowed !== isLogin) {
      nav(redirectTo);
    }
  }, [isLogin, allowed, redirectTo, nav]);

  return allowed === isLogin ? <>{children}</> : <></>;
};

export default AuthRoute;

// 方案二
// if (allowed !== isLogin) {
//   return <Navigate to={redirectTo}/>;
// }
// return <>{children}</>;
